//
//  YSHomeCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/6/28.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSHomeCtrl.h"
#import "JXScrollBar.h"
#import "YSHomeDataTool.h"
#import "YSRecommendCtrl.h"
#import "YSHistoryCtrl.h"
#import "YSLoginCtrl.h"
#import "CustomNavigationCtrl.h"
#import "CartView.h"
#import <BaiduMapAPI/BMapKit.h>//refer all head file
#import "YSModifyInfoCtrl.h"
#import "YSCommonReqTool.h"


@interface YSHomeCtrl ()<UIScrollViewDelegate,JXScrollBarDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>

@property(nonatomic,strong)BMKLocationService *locService;
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)NSMutableArray *childController;
@property(nonatomic,strong)NSMutableArray *titleArray;
@property(nonatomic,strong)JXScrollBar *scrollBar;
@property(nonatomic,strong)CartView *cartView;
@property (strong,nonatomic) UIImageView *titleLogoView;

@end

@implementation YSHomeCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initBaiduMapLocation];
    [self updateCartIndex];
    
    _childController = [NSMutableArray array];
    _titleArray = [NSMutableArray array];
    [_titleArray addObject:@"悦食市集"];
    [_titleArray addObject:@"往期热读"];

    CartView *cartView = [[CartView alloc]initWithImage:@"btn_cart"];
    [cartView addTarget:self action:@selector(tapTitleRightItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:cartView];
    _cartView = cartView;

    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, SCREENW, SCREENH);
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.pagingEnabled = YES;
    //设置scrollview的代理
    scrollView.delegate = self;
    scrollView.scrollsToTop = NO;
    _scrollView = scrollView;
    [self.view addSubview:scrollView];

    JXScrollBar *scrollBar = [[JXScrollBar alloc]initWithFrame:CGRectMake(0, 0, SCREENW-16, 44) type:JXScrollBarSplitTypeCenter];
    scrollBar.delegate = self;
    _scrollBar = scrollBar;
    self.navigationItem.titleView = _scrollBar;
    [self inflateLayout];
    
    [_cartView setHidden:YES];
    [_scrollBar setHidden:YES];
    
    [self addTitleAnimLogo];
}

-(void)addTitleAnimLogo{
    //添加首页的顶部动画
    UIImage *logoImg = [UIImage imageNamed:@"home_title_logo"];
    UIImageView *titleLogoView  = [[UIImageView alloc]initWithImage:logoImg];
    titleLogoView.userInteractionEnabled = YES;
    [titleLogoView setX:(SCREENW-logoImg.size.width)/2];
    CGFloat statubarH = [UIApplication sharedApplication].statusBarFrame.size.height;
    [titleLogoView setY:(NavWithStatusBarH+statubarH-logoImg.size.height)/2];
    [theApp.window addSubview:titleLogoView];
    _titleLogoView = titleLogoView;
    
    //执行logo动画
    titleLogoView.transform = CGAffineTransformMakeScale(0.01f,0.01f);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationDelegate:self];
    titleLogoView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
    [UIView setAnimationDidStopSelector:@selector(animFinish)];
    [UIView commitAnimations];
}

-(void)animFinish{
    //缩放动画执行完毕停留1秒，执行淡出动画
    [NSThread sleepForTimeInterval:1.0];
    [_scrollBar setHidden:NO];
    [_cartView setHidden:NO];
    [UIView animateWithDuration:1.0 animations:^{
        [_titleLogoView setAlpha:0.0f];
        _titleLogoView.y = _titleLogoView.y-YSPublicXInset*2;
    } completion:^(BOOL finished) {
        [_titleLogoView removeFromSuperview];
    }];
}

-(void)updateCartIndex{
    //更新购物篮角标
    if(ISLOGIN){
        __weak typeof (self) weakSelf = self;
        [[YSCommonReqTool sharedTool] loadIndex:YSBadgeCartType callback:^(NSInteger count) {
             [weakSelf.cartView setNum:count];
        }];
    }else{
         [DefaultsHelper setInteger:0 forKey:kCartIndex];
    }
}

-(void)tapTitleRightItem:(UIBarButtonItem *)btnItem{
    [Utils showCartCtrl:self];
}

-(void)inflateLayout{
    for (UIViewController *ctrl in _childController) {
        [ctrl.view removeFromSuperview];
    }
    [_childController removeAllObjects];
    //添加推荐页
    YSRecommendCtrl *recommendCtrl = [[YSRecommendCtrl alloc]init];
    [_childController addObject:recommendCtrl];
    UIView *recommendView = recommendCtrl.view;
    recommendView.frame =CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH);
    [_scrollView addSubview:recommendView];
    //添加往期页
    YSHistoryCtrl *historyCtrl = [[YSHistoryCtrl alloc]init];
    [_childController addObject:historyCtrl];
    UIView *historyView = historyCtrl.view;
    historyView.frame =CGRectMake(SCREENW, 0, SCREENW, SCREENH-NavWithStatusBarH-BottomTabarH);
    [_scrollView addSubview:historyView];
    //设置scrollBar的数据
    [_scrollBar setTitleArray:_titleArray];
    [_scrollBar scrollViewDidScroll:_scrollView];
    //使第1页去加载数据
    [self scrollViewDidEndDecelerating:_scrollView];
     _scrollView.contentSize = CGSizeMake(_titleArray.count*SCREENW, 0);
}

#pragma mark -jxscrollbar代理，处理点击title的button事件
- (void)titleClicked:(JXScrollBar *)scrollbar index:(int)index{
    [scrollbar autoScrollToCenter:index];
    [self setScrollCurrentPageNum:index];
}

#pragma mark -滚动代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_scrollBar scrollViewDidScroll:scrollView];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //当前页数
    int pageNum = (scrollView.contentOffset.x+scrollView.width*0.5)/scrollView.width;
    
    [self setScrollCurrentPageNum:pageNum];
    [_scrollBar scrollViewDidEndDecelerating:scrollView];
}

-(void)setScrollCurrentPageNum:(int)pageNum{
    CGPoint p = CGPointMake(pageNum*_scrollView.frame.size.width, 0);
    [_scrollView setContentOffset:p];
    //这句代码的作用是解决点击顶部之后底部的scrollview往上跑的问题
    _scrollView.y = 0;
    if ([_childController[pageNum] isKindOfClass:[YSRecommendCtrl class]]) {
        YSRecommendCtrl *recommend = _childController[pageNum];
       [recommend checkRequestData];
    }else{
        YSHistoryCtrl *history = _childController[pageNum];
       [history checkRequestData];
    }
}

-(void)initBaiduMapLocation{
    //set location accuracy，default：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //assign min distance update(meter)，default：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    //init BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //start LocationService
    [_locService startUserLocationService];
}
//implemention relevance delegate, deal with location info update ,deal with orientation update info
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
}
//deal with location info update
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    if(userLocation.location){
        NSLog(@"\n百度到位置:\n  纬度lat:%f\n  经度lng:%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        BMKGeoCodeSearch *geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
        geoCodeSearch.delegate  = self;
        //initialize geography encode class
        BMKReverseGeoCodeOption *reverseGeoCodeOption = [[BMKReverseGeoCodeOption alloc]init];
        //need backwards geography encode's location
        reverseGeoCodeOption.reverseGeoPoint = userLocation.location.coordinate;
        [geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
        [_locService stopUserLocationService];
    }
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    //get city
    NSString *city =  result.addressDetail.city;
    NSString *province = result.addressDetail.province;
    NSString *area = result.addressDetail.district;
    NSString *streetName = result.addressDetail.streetName;
    
    [DefaultsHelper setObject:province forKey:kLocationAddressProvince];
    [DefaultsHelper setObject:city forKey:kLocationAddressCity];
    [DefaultsHelper setObject:area forKey:kLocationAddressArea];
    [DefaultsHelper setObject:streetName forKey:kLocationAddressStreet];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSDictionary *userInfo = [DefaultsHelper dictionaryForKey:kRemotePushNortif];
    if (userInfo) {
        CustomNavigationCtrl *navCtl = (CustomNavigationCtrl *)self.navigationController;
        [navCtl dealNoti:userInfo isEnterForeground:YES];
        [DefaultsHelper setObject:nil forKey:kRemotePushNortif];
    }
    
    if(_cartView){
       NSInteger num = [DefaultsHelper integerForKey:kCartIndex];
       [_cartView setNum:num];
    }
}

@end
